package com.icngor.ch07;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Vcode extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public Vcode() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int width = 60;
		int height = 30;
		
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setFont(new Font("Times New Roman",Font.BOLD,20));
		Random random = new Random();
		String vcode = "";
		for(int i = 0 ; i< 4; i++){
			String rand = String.valueOf(random.nextInt(10));
			vcode+=rand;
			g.drawString(rand,15*i+5,20);

		}
		HttpSession session = request.getSession();
		session.setAttribute("vcode", vcode);
		g.dispose();
		ImageIO.write(image, "jpeg", response.getOutputStream());
	
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

	static public String getVcode(HttpSession session){
		return (String) session.getAttribute("vcode");
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
